<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form
    class="p-4 enter-x"
    :model="formData"
    :rules="getFormRules"
    ref="formRef"
    v-show="getShow"
    @keypress.enter="handleLogin"
  >
    <FormItem name="userName" class="enter-x">
      <Input
        size="large"
        v-model:value="formData.userName"
        :placeholder="`${t('sys.login.userName')}/${t('sys.login.mobile')}/${t('sys.login.email')}`"
        class="fix-auto-fill"
      >
        <template #prefix>
          <Icon icon="ant-design:user-outlined" />
        </template>
      </Input>
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="t('sys.login.password')"
      >
        <template #prefix>
          <Icon icon="carbon-password" />
        </template>
      </InputPassword>
    </FormItem>

    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <!-- <Checkbox v-model:checked="rememberMe" size="small">
            {{ t('sys.login.rememberMe') }}
          </Checkbox> v-if="confirmMail || confirmPhone"-->
          <Button type="link" size="small" @click="handleConfirm">
            {{
              confirmMail
                ? t('sys.login.sendConfirmEmail')
                : confirmPhone
                  ? t('sys.login.confirmPhone')
                  : ''
            }}
          </Button>
        </FormItem>
      </ACol>
      <ACol :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol>
    </ARow>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
    </FormItem>
    <ARow class="enter-x" :gutter="[16, 16]">
      <ACol :md="hasRegister ? 8 : 12" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="hasRegister ? 8 : 12" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('sys.login.qrSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="hasRegister ? 8 : 12" :xs="24" v-if="hasRegister">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
        </Button>
      </ACol>
    </ARow>
    <Divider
      class="enter-x"
      v-if="
        oAuth2InfoRef.WeChat ||
        oAuth2InfoRef.DingTalk ||
        oAuth2InfoRef.TikTok ||
        oAuth2InfoRef.QQ ||
        oAuth2InfoRef.Microsoft ||
        oAuth2InfoRef.GitHub
      "
    >
      {{ t('sys.login.otherSignIn') }}
    </Divider>
    <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <Tooltip
        :title="t('sys.login.signInWithWeChat')"
        placement="bottom"
        v-if="oAuth2InfoRef.WeChat"
      >
        <span @click="handleOAuth2Login('WeChat')">
          <Icon icon="ant-design:wechat-outlined" :size="30" />
        </span>
      </Tooltip>
      <Tooltip
        :title="t('sys.login.signInWithDingTalk')"
        placement="bottom"
        v-if="oAuth2InfoRef.DingTalk"
      >
        <span @click="handleOAuth2Login('DingTalk')">
          <Icon icon="ant-design:dingtalk-outlined" :size="30" />
        </span>
      </Tooltip>
      <Tooltip
        :title="t('sys.login.signInWithDouYin')"
        placement="bottom"
        v-if="oAuth2InfoRef.TikTok"
      >
        <span @click="handleOAuth2Login('TikTok')">
          <Icon icon="ic:twotone-tiktok" :size="30" />
        </span>
      </Tooltip>
      <Tooltip :title="t('sys.login.signInWithQQ')" placement="bottom" v-if="oAuth2InfoRef.QQ">
        <span @click="handleOAuth2Login('QQ')">
          <Icon icon="ant-design:qq-outlined" :size="30" />
        </span>
      </Tooltip>
      <Tooltip
        :title="t('sys.login.signInWithMicrosoft')"
        placement="bottom"
        v-if="oAuth2InfoRef.Microsoft"
      >
        <span @click="handleOAuth2Login('Microsoft')">
          <Icon icon="prime:microsoft" :size="30" />
        </span>
      </Tooltip>
      <Tooltip
        :title="t('sys.login.signInWithGitHub')"
        placement="bottom"
        v-if="oAuth2InfoRef.GitHub"
      >
        <span @click="handleOAuth2Login('GitHub')">
          <Icon icon="ant-design:github-outlined" :size="30" />
        </span>
      </Tooltip>
    </div>

    <div class="justify-evenly enter-x" style="margin-top: 20px; font-size: small">
      <span>{{ t('sys.app.copyright', { endyear: currentyear }) }}</span>
    </div>
    <div class="justify-evenly enter-x" style="margin-top: 10px; font-size: small">
      <span>
        {{ t('sys.app.recommendedUse') }}
        <a href="//www.google.cn/intl/zh-CN/chrome/" target="_blank">
          {{ t('sys.app.googleChrome') }}
        </a>
        {{ `、` }}
        <a href="//www.microsoft.com/zh-cn/edge" target="_blank">
          {{ t('sys.app.microsoftEdge') }}
        </a>
        {{ t('sys.app.visit') }}
      </span>
    </div>
  </Form>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, computed, watchEffect, h } from 'vue';

  import { Form, Input, Row, Col, Button, Divider, Tooltip } from 'ant-design-vue';

  import LoginFormTitle from './LoginFormTitle.vue';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';

  import { useIdentityStore } from '@/store/modules/identity';
  import { RequestClientTypeEnum } from '@/api/identity/model';
  import { oAuth2Login } from '@/api/identity';
  import { getOAuth2Info } from '@/api/sys';

  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '@/hooks/web/useDesign';
  import { usePermission } from '@/hooks/web/usePermission';
  // import { useGlobSetting } from '@/hooks/setting';
  import Icon from '@/components/Icon/Icon.vue';

  import { urlEncode } from '@/utils/common';

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;

  const currentDate = new Date();
  const currentyear = currentDate.getFullYear();

  const { hasPermission } = usePermission();
  // const { id } = useGlobSetting();
  const { t } = useI18n();
  const { notification, createErrorModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const identityStore = useIdentityStore();

  const { setLoginState, getLoginState, setUserAccount, getUserAccountState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const loading = ref(false);
  // const rememberMe = ref(false);
  const oAuth2InfoRef = ref<any>({});

  const confirmMail = ref(false);
  const confirmPhone = ref(false);

  const formData = reactive({
    userName: '',
    password: '',
  });

  watchEffect(async () => {
    const userAccountState = computed(() => unref(getUserAccountState));
    formData.userName = userAccountState.value;

    oAuth2InfoRef.value = await getOAuth2Info();
  });

  const { validForm } = useFormValid(formRef);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

  const hasRegister = computed(() => hasPermission('Root.Identity.Register'));

  /** 处理登录 */
  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      setUserAccount(data.userName);
      const userInfo = await identityStore.login({
        GrantType: 'password',
        Account: data.userName,
        Password: data.password,
        OrganizationId: null,
        ClientType: RequestClientTypeEnum.Browser,
        ClientId: null,
        RefreshToken: null,
        VerifyCode: null,
        VerifyCodeId: null,
        mode: 'none', //不要默认的错误提示
      });
      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.NickName}`,
          duration: 3,
        });
      }
    } catch (error) {
      // 处理邮箱未验证标识
      confirmMail.value = (error as unknown as Error)?.message.indexOf('邮箱未验证') > -1;
      // 处理手机未验证标识
      confirmPhone.value = (error as unknown as Error)?.message.indexOf('手机未验证') > -1;

      showErrorModal(
        t('sys.api.errorTip'),
        (error as unknown as Error)?.message || t('sys.api.networkExceptionMsg'),
      );
    } finally {
      loading.value = false;
    }
  }

  /** 处理激活邮箱手机 */
  async function handleConfirm() {
    if (confirmMail.value) {
      setLoginState(LoginStateEnum.SEND_CONFIRM_EMAIL);
    } else if (confirmPhone.value) {
      setLoginState(LoginStateEnum.CONFIRM_PHONE);
    }
    confirmMail.value = false;
    confirmPhone.value = false;
  }

  /**
   * 处理OAuth2三方登录，跳转至登录页
   * @param type 登录类型
   */
  function handleOAuth2Login(
    type: 'WeChat' | 'DingTalk' | 'TikTok' | 'QQ' | 'Microsoft' | 'GitHub',
  ) {
    const callback = `/#/callback/${type}`;
    const urlParams = `provider=${type}&returnUrl=${urlEncode(callback)}`;
    oAuth2Login(urlParams);
  }

  function showErrorModal(title: string, content: string) {
    createErrorModal({
      title: () => h('span', title),
      content: () => h('span', content),
      getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
    });
  }
</script>
